<?php

namespace App\Model;

use App\BaseModel;
use Illuminate\Support\Facades\DB;

class Activity extends BaseModel
{
    protected $table = "activities";

    protected $fillable = [
        'toll',
        'type',
        'state',
        'name',
        'abstract',
        'covers',
        'detail_text',
        'detail_pic',
        'lecturer_id',
        'participate_limit',
        'need_share',
        'share_rule',
        'start_time',
        'end_time',
        'deadline',
        'location',
        'cost_type',
        'cost',
        'user_id',
        'creator',
        'updater',
        'next_id',
    ];

    public function setCoversAttribute($value)
    {
        $this->attributes['covers'] = json_encode($value);
    }

    public function nextActivity()
    {
        return $this->belongsTo('App\Model\Activity','next_id','id');
    }

    public function getCoversAttribute($value)
    {
        return json_decode($value);
    }

    public function setDetailPicAttribute($value)
    {
        $this->attributes['detail_pic'] = json_encode($value);
    }

    public function getDetailPicAttribute($value)
    {
        return json_decode($value);
    }

    public function products()
    {
        return $this->belongsToMany('App\Model\WineProduct','activity_products',
            'activity_id','product_id');
    }

    public static function getFreeSignPassCount($id)
    {
        return DB::table('activity_orders')->where('activity_id','=',$id)
            ->whereNull('deleted_at')
            ->whereIn('state',[3,4,5])->count();
    }

    public static function updateSignCount($id)
    {
        DB::table('activities')->where('id','=',$id)->update([
            'sign_count' => DB::table('activity_orders')->where('activity_id','=',$id)->whereNull('deleted_at')
                ->whereIn('state',[3,4,5,7])->count(),
        ]);

        return DB::select('update activities set state="finished" where participate_limit<=sign_count');

    }
}
